set(CMAKE_SYSTEM_NAME Generic)
set(CMAKE_SYSTEM_VERSION 1)
cmake_minimum_required(VERSION 3.22)

include(./FindFiles.cmake)
# specify cross-compilers and tools
set(CMAKE_C_COMPILER "arm-none-eabi-gcc")
set(CMAKE_CXX_COMPILER "arm-none-eabi-g++")
set(CMAKE_ASM_COMPILER  "arm-none-eabi-gcc")
set(CMAKE_AR "arm-none-eabi-ar")
set(CMAKE_OBJCOPY "arm-none-eabi-objcopy")
set(CMAKE_OBJDUMP "arm-none-eabi-objdump")
set(SIZE "arm-none-eabi-size")

set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/Output)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/Output/Lib)
# project settings
project(STM32G474RET6 C CXX ASM)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_C_STANDARD 11)

add_definitions(-DSTM32G474xx -DUSE_HAL_DRIVER)
set(FullPath "Core" "USB_DEVICE" "User" "Drivers" "Middlewares" "CANOpen")
set(NotPath "build" "Lib" "CherryUSB" "Output" "Doc")
SerchRoot(addr NotPath)
SourceIncAndSrc(Src Inc addr)
# message("${Src}\r\n${Inc}")
message("正在编译 ${PROJECT_NAME} ${CMAKE_BUILD_TYPE} 版本")
message("C ${CMAKE_C_STANDARD} / C++ ${CMAKE_CXX_STANDARD} 标准")
message("可执行文件输出目录: ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}")
message("静态库输出目录: ${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}")

# add_subdirectory(CherryUSB)
file(GLOB LINKER_SCRIPT ${CMAKE_SOURCE_DIR}/*FLASH.ld)
add_executable(${PROJECT_NAME}.elf ${Src} ${LINKER_SCRIPT})
# add_dependencies(${PROJECT_NAME}.elf cherryusb)
target_include_directories(${PROJECT_NAME}.elf 
        PUBLIC  ${Inc} CherryUSB/common)
target_compile_options(${PROJECT_NAME}.elf 
        PUBLIC  -mcpu=cortex-m4 -mfloat-abi=hard -mfpu=fpv4-sp-d16)
        target_link_options(${PROJECT_NAME}.elf 
        PUBLIC  -mcpu=cortex-m4 -mfloat-abi=hard -mfpu=fpv4-sp-d16
                --specs=${CMAKE_SOURCE_DIR}/standard_c_nano_cpp.specs -u _printf_float -Wl,--start-group -lc -lm -lstdc++ -lsupc++ -Wl,--end-group -T ${LINKER_SCRIPT} -Wl,-Map=${PROJECT_BINARY_DIR}/${PROJECT_NAME}.map,--cref -Wl,--gc-sections,--print-memory-usage -static
)
target_link_libraries(${PROJECT_NAME}.elf
        PUBLIC -lmp-G4-IAR_ARMv7-M -larm_cortexM4lf_math -L${CMAKE_SOURCE_DIR}/MCSDK/MotorControl/libMP -L${CMAKE_SOURCE_DIR}/Output/Lib -L${CMAKE_SOURCE_DIR}/Middlewares/ST/ARM/DSP/Lib
)
set(CMAKE_C_FLAGS "-Wall -fdata-sections -ffunction-sections")
set(CMAKE_ASM_FLAGS "-Wall -fdata-sections -ffunction-sections")
set(CMAKE_CXX_FLAGS "-Wall -Wno-psabi -fdata-sections -ffunction-sections -fno-exceptions -fno-use-cxa-atexit -fstack-usage")

set(HEX_FILE ${CMAKE_SOURCE_DIR}/Output/${PROJECT_NAME}.hex)
set(BIN_FILE ${CMAKE_SOURCE_DIR}/Output/${PROJECT_NAME}.bin)

add_custom_command(TARGET ${PROJECT_NAME}.elf POST_BUILD
        COMMAND ${CMAKE_OBJCOPY} -Oihex $<TARGET_FILE:${PROJECT_NAME}.elf> ${HEX_FILE}
        COMMAND ${CMAKE_OBJCOPY} -Obinary $<TARGET_FILE:${PROJECT_NAME}.elf> ${BIN_FILE}
        COMMENT "Building ${HEX_FILE}
Building ${BIN_FILE}")
